#include "main.h"

		
#include "stdlib.h"
#include "string.h"
#include "user_uart_interrupt.h"
#include "main.h"
#include "user_gpio.h"
#include "user_delay.h"
#include "bstim32_timing.h"
#include "user_adc.h"
#include <stdio.h> 
#include "BC26.h"
#include "TelecomPlatform.h"
#include "Network_communication.h"
#include "MHL10.h" 
#include "M120L.h"




	
#define VERSION "air-sys-6in1-v1.02-20211225"



	
extern uint8_t UART0_Rx_Buf[MAX_REC_LENGTH];
extern uint16_t  UART0_Rx_cnt;
extern uint8_t UART0_temp[REC_LENGTH];

uint8_t Wireless_RSSI;
uint8_t Dest_IP[16]={'l','p','w','a','n','.','i','o','t','.','s','t','o','r','e',0};
uint8_t Dest_PORT[6]={'1','0','0','0','7',0};
uint8_t Tx_Err_Cnt = 0;
uint8_t HeartBeat_Packet[83]={'3','0','3','0','4','E'}; 
uint8_t HW_SW_Version[3]={'1','1',0};
uint32_t bstim_cnt = 0;
uint32_t  GetVoltage;

uint16_t Ref_Val;
uint16_t Battary_Val;
uint16_t adc_calt_value;

uint16_t ordor_data;

uint8_t Wireless_Mode = Nb_Mode;
uint8_t LoRa_1freq_CH = LoRa_1freq_ch0;

measure_value MeasureData={0,0};

uint8_t Sent_Data[100]={'2','4','2','4','0','0','8','8'};
uint8_t MHL10_TxData[50];
uint8_t Sample_Data[16];
uint8_t M120L_TxData[50];

int8_t	SocketId=-1;
uint8_t	Send_err_time=0;
uint8_t 	SendMessageFlag=0;
uint8_t	  Bc26_Initial_Flag=FALSE;
uint8_t Bc26_CESQ;

uint8_t LoRa_Detect = 0; 
uint8_t LoRa_Config = 0; 

uint8_t LoRaWAN_Detect = 0; 

uint8_t Rece_len;
uint8_t Recebuffer[ReceiveUdpDataMaxLen];

uint8_t Simcard_exist = 0x00;

uint16_t MeasureTimes = 0x00;
uint8_t SentTimes = 0x00;

uint8_t INT_KEY_DOWN = KEY_UP;

uint16_t Period_Sample = 20; 
uint16_t PeriodSent_MeasureTimes = 1800;  
uint16_t Reboot_MeasureTimes = 43200; 
uint8_t Period_Green_led = 10; 
uint8_t Period_Red_led = 2; 


uint8_t Period_Sent_Flag = 0;
uint8_t NIC_Sent_Flag = 0;
uint8_t Alarm_Sent_Flag = 0;

uint32_t Alarm_cnt = 0;
uint32_t Alarm_Normal_Interval = 300; 
uint16_t PM2_5_High_th = 500;
uint16_t PM2_5_Low_th = 300;
uint8_t Alarm_Status = 0;





	
char lowhextoascii(char hexdata)
{
	char temp;
	temp=hexdata&0x0f;
	if(temp<10)
		temp=temp+0x30;
	else
		temp=temp+0x37;
	return temp;
}


void LED_blink(uint8_t time)
{
	while(time--)
	{
		LED5_ON;
		HAL_Delay(100);
		LED5_OFF;
		HAL_Delay(100);
	}
}


void Nb_Data_Communication(void)
{
	uint8_t  Result=FALSE;
	uint8_t i;
	if(SocketId<0)
	{
		SocketId=BC26_IntialAndCreatSocket();
	}
	else
	{	
		SysPrintf(">>wakeup bc26\r\n");
		BC26_EINT3V3_H;
		HAL_Delay(30);
		BC26_EINT3V3_L;
		HAL_Delay(1000);
	}
	if(SocketId>=0)
	{
		Bc26_CESQ=BC26_Check_CESQ();
		Result=SendMessage_To_Server();
		
		if(Result==TRUE)
		{
			LED_blink(5);
			SysPrintf("sent data success and wait cmd\r\n");
			Send_err_time = 0;			
			Receive_Message_From_Server();
			if(Rece_len>0)
			{
				SysPrintf("receive nb cmd len=%d\n",Rece_len);
				SysPrintf("receive nb cmd=%s\n",Recebuffer);
				LED_blink(3);
				CMDProcess(Recebuffer,Rece_len);
				Rece_len = 0;
				for(i=0;i<ReceiveUdpDataMaxLen;i++)
					Recebuffer[i] = 0;
			}
								    	
		}
		else
		{
			LED_blink(1);
			SysPrintf("sent data fail and try again\r\n");
			Send_err_time++;
			Result=SendMessage_To_Server(); 
			if(Result==TRUE)
			{
				LED_blink(5);
				SysPrintf("sent data success and wait cmd\r\n");
				Send_err_time = 0;				    				
				Receive_Message_From_Server();
				if(Rece_len>0)
				{
					SysPrintf("receive nb cmd len=%d\n",Rece_len);
					SysPrintf("receive nb cmd=%s\n",Recebuffer);
					LED_blink(3);
					CMDProcess(Recebuffer,Rece_len);
					Rece_len = 0;
					for(i=0;i<ReceiveUdpDataMaxLen;i++)
					Recebuffer[i] = 0;
				}
			}
			else
			{
				LED_blink(1);
				Send_err_time++;
				SysPrintf("sent data fail again\r\n");
				
			}

			if(Send_err_time>=4)
			{
				Send_err_time=0;
				SocketId=-1;	
				SysPrintf("SocketId=-1\n");
			}
		}
	}
	else
	{
		SysPrintf("nb initial and creatsocket err\r\n");
		Send_err_time=0;
		SocketId=-1;	
		SysPrintf("SocketId=-1\r\n");			
	}
	Bc26_Initial_Flag=BC26_ConfigSleepMode(BC26_EnableSleepMode);
}



void Lora_Data_Communication(void)
{
	uint8_t i;
	uint8_t j = 0;
	uint8_t Sent_ret = 0;
	
	for(i=0;i<8;i++)  
		MHL10_TxData[i] = Sent_Data[i];
	
	MHL10_TxData[16] = Sent_Data[43]; 
	
	Sample_Data[1] = MeasureData.PM1_0;
	Sample_Data[0] = MeasureData.PM1_0>>8;
	Sample_Data[3] = MeasureData.PM2_5;
	Sample_Data[2] = MeasureData.PM2_5>>8;
	Sample_Data[5] = MeasureData.PM10;
	Sample_Data[4] = MeasureData.PM10>>8;
	Sample_Data[7] = MeasureData.VOC;
	Sample_Data[6] = MeasureData.VOC>>8;
	Sample_Data[9] = MeasureData.temperature;
	Sample_Data[8] = MeasureData.temperature>>8;
	Sample_Data[11] = MeasureData.humi;
	Sample_Data[10] = MeasureData.humi>>8;
	Sample_Data[12] = 0x00;
	Sample_Data[13] = SentTimes;
	Sample_Data[14] = 0x00; 
	Sample_Data[15] = 0xAA; 
	
	
	for(i=0;i<16;i++)
	{
		sprintf(MHL10_TxData+17+j*2,"%02x",Sample_Data[i]);
		++j;
	}
	MHL10_TxData[49] = 0;

	SysPrintf("LoRa sent data:%s\r\n",MHL10_TxData);
	
	if(Send_err_time>=4)
	{
		Send_err_time=0;
		MHL10_Initial_Config();	
	}
	
	
	Sent_ret = MHL10_Sent_Packet_To_Gateway(MHL10_TxData,49);
	if(Sent_ret==2) 
	{
		LED_blink(5);	
		Send_err_time = 0;
		if(Rece_len>0)
		{
			SysPrintf("receive LoRa cmd len=%d\n",Rece_len);
			SysPrintf("receive LoRa cmd=%s\n",Recebuffer);
			LED_blink(3);
			CMDProcess(Recebuffer,Rece_len);
			Rece_len = 0;
			for(i=0;i<ReceiveUdpDataMaxLen;i++)
				Recebuffer[i] = 0;
		}
	}
	else if(Sent_ret==1) 
	{
		LED_blink(5);
		; 
		Send_err_time = 0;
	}
	else if(Sent_ret==0)
	{
		LED_blink(1);	
		Send_err_time++;
		SysPrintf("sent data fail and try again\r\n");
		Sent_ret = MHL10_Sent_Packet_To_Gateway(MHL10_TxData,49);
		if(Sent_ret==2)
		{
			LED_blink(5);
			Send_err_time = 0;
			if(Rece_len>0)
			{
				SysPrintf("receive lora cmd len=%d\n",Rece_len);
				SysPrintf("receive lora cmd=%s\n",Recebuffer);
				LED_blink(3);
				CMDProcess(Recebuffer,Rece_len);
				Rece_len = 0;
				for(i=0;i<ReceiveUdpDataMaxLen;i++)
					Recebuffer[i] = 0;
			}
		}
		else if(Sent_ret==1)
		{
			LED_blink(5);
			; 
			Send_err_time = 0;
		}
		else if(Sent_ret==0)
		{
			LED_blink(1);
			Send_err_time++;
			SysPrintf("sent data fail again\r\n");
		}
	}

    LED0_OFF;		
	SendMessageFlag=0;

}

void LoraWAN_Data_Communication(void)
{
	uint8_t i;
	uint8_t j = 0;
	int8_t LoRaWAN_JOIN_Status;
	int8_t LoRaWAN_Sent_Status;
	int8_t LoRaWAN_Sleep_ret;
	for(i=0;i<8;i++)  
		M120L_TxData[i] = Sent_Data[i];
	M120L_TxData[8] = Sent_Data[43];
	Sample_Data[1] = MeasureData.PM1_0;
	Sample_Data[0] = MeasureData.PM1_0>>8;
	Sample_Data[3] = MeasureData.PM2_5;
	Sample_Data[2] = MeasureData.PM2_5>>8;
	Sample_Data[5] = MeasureData.PM10;
	Sample_Data[4] = MeasureData.PM10>>8;
	Sample_Data[7] = MeasureData.VOC;
	Sample_Data[6] = MeasureData.VOC>>8;
	Sample_Data[9] = MeasureData.temperature;
	Sample_Data[8] = MeasureData.temperature>>8;
	Sample_Data[11] = MeasureData.humi;
	Sample_Data[10] = MeasureData.humi>>8;
	Sample_Data[12] = 0x00;
	Sample_Data[13] = SentTimes;
	Sample_Data[14] = 0x00; 
	Sample_Data[15] = 0xAA; 
	
	
	for(i=0;i<16;i++)
	{
		sprintf(M120L_TxData+9+j*2,"%02x",Sample_Data[i]);
		++j;
	}
	M120L_TxData[41] = 0;

	SysPrintf("LoRaWAN sent data:%s\r\n",M120L_TxData);
	
	M120_Wakeup_INT();
	
	if(Send_err_time>=4)
	{
		Send_err_time=0;
		LoRaWAN_Detect = 0;
		M120_Initial();	
	}
	LoRaWAN_JOIN_Status =  Get_M120_Status_INT();
	if(LoRaWAN_JOIN_Status == -1) 
	{
		M120_Join_Net_INT();
		LoRaWAN_JOIN_Status =  Get_M120_Status_INT();
		if(LoRaWAN_JOIN_Status==-1) 
		{
			Send_err_time++;
		}
		else 
		{
			LoRaWAN_Sent_Status = M120_TxData_INT(M120L_TxData, 41);
			if(LoRaWAN_Sent_Status==-1)
			{
				Send_err_time++;
				LED1_ON;
				HAL_Delay(100);
				LED1_OFF;		
			}
			else
			{
				Send_err_time = 0;
				M120_RecvData_INT();
				if(Rece_len>0)
				{
					SysPrintf("receive lorawan cmd len=%d\n",Rece_len);
					SysPrintf("receive lorawan cmd=%s\n",Recebuffer);
					LED_blink(3);
					CMDProcess(Recebuffer,Rece_len);
					Rece_len = 0;
					for(i=0;i<ReceiveUdpDataMaxLen;i++)
						Recebuffer[i] = 0;
				}
			}
		}
	}
	else if(LoRaWAN_JOIN_Status == 1) 
	{
		LoRaWAN_Sent_Status = M120_TxData_INT(M120L_TxData, 41);
		if(LoRaWAN_Sent_Status==-1)
		{
			Send_err_time++;
			LED1_ON;
			HAL_Delay(100);
			LED1_OFF;
		}
		else
		{
			Send_err_time = 0;
			M120_RecvData_INT();
			if(Rece_len>0)
			{
				SysPrintf("receive lorawan cmd len=%d\n",Rece_len);
				SysPrintf("receive lorawan cmd=%s\n",Recebuffer);
				LED_blink(3);
				CMDProcess(Recebuffer,Rece_len);
				Rece_len = 0;
				for(i=0;i<ReceiveUdpDataMaxLen;i++)
					Recebuffer[i] = 0;
			}
		}
	}
	else
	{
		;
	}
	
	LoRaWAN_Sleep_ret = M120_sleep01_INT();
	if(LoRaWAN_Sleep_ret==-1)
	{
		LoRaWAN_Sleep_ret = M120_sleep01_INT();
		if(LoRaWAN_Sleep_ret==-1)
		{
			NB_PW_OFF;
			LoRaWAN_Detect = 0;
		}
	}

}






/**
  ****************************************************************************************************
  * @file    main.c
  * @author  FMSH Application Team
  * @brief   Header file of FL Module
  ****************************************************************************************************
  * @attention
  *
  * Copyright (c) [2019] [Fudan Microelectronics]
  * THIS SOFTWARE is licensed under the Mulan PSL v1.
  * can use this software according to the terms and conditions of the Mulan PSL v1.
  * You may obtain a copy of Mulan PSL v1 at:
  * http:
  * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
  * PURPOSE.
  * See the Mulan PSL v1 for more details.
  *
  ****************************************************************************************************
  */
  
int main(void)
{
    
		
		
		uint8_t i;
	
    
    MF_Clock_Init();

    
    
    FL_Init();

    
    

    MF_Config_Init();
		
	
	
	
	bstim_cnt = 0;
	i = 10;
	SysPrintf("%s\r\n",VERSION);
	/*
	while(1)
	{
		UART0_Rx_cnt = 0;
		SendDataToLoRaWANModule(M120_deveui_cmd,12);
		HAL_Delay(2000);
		SysPrintf("len=%d\r\n",UART0_Rx_cnt);
		UART0_Rx_Buf[UART0_Rx_cnt]=0 ;
		SysPrintf("Recv:%s\n",UART0_Rx_Buf);
	}
	*/
	BSTIM32_Start();
	Get_Commu_Type();
	LED1_OFF;
	LED0_ON;
	LED5_OFF;
	LED4_ON;
	NB_PW_OFF;

	

	
	if((Wireless_Mode==Lora_Mode) || (Wireless_Mode>=LoRa_1freq_Mode))
	{
		while(i--)
		{
			if(FL_GPIO_GetInputPin(WAKEUP0_GPIO_Port,WAKEUP0_Pin)==0)
			{
				SysPrintf("key down...\r\n");
				HAL_Delay(1000);
				if(FL_GPIO_GetInputPin(WAKEUP0_GPIO_Port,WAKEUP0_Pin)==0)
				{
					LoRa_Config = 1;
					SysPrintf("sys will config lora freq info...\r\n");
				}
				else
				{
					LoRa_Config = 0;
				}
				break;
			}
			HAL_Delay(300);
		}
			
	}
 LED0_OFF;
	
	
	Get_PM_Data();
	Get_RS485_TempHumi();
	Get_Ordor_Data();
	
	
	if(Wireless_Mode==Nb_Mode)
	{
		SysPrintf("Commu-type:NB-IoT\r\n");
		Sent_Data[6] = '4';
		Sent_Data[7] = '4';
		SocketId=BC26_IntialAndCreatSocket();
	}
	else if(Wireless_Mode==Lora_Mode)
	{
		Sent_Data[6] = '2';
		Sent_Data[7] = '9';
		SysPrintf("Commu-type:LoRa\r\n");
		MHL10_Initial_Config();
	}
	else if(Wireless_Mode==LoRaWAN_Mode)
	{
		Sent_Data[6] = '2';
		Sent_Data[7] = '1'; 
		SysPrintf("Commu-type:LoRaWAN\r\n");
		M120_Initial();
		
	}
	else if(Wireless_Mode>=LoRa_1freq_Mode)
	{
		Sent_Data[6] = '2';
		Sent_Data[7] = '9';
		SysPrintf("Commu-type:LoRa_1freq_Mode\r\n");
		MHL10_Initial_Config();
	}
	else
	{
		SysPrintf("Commu-type:error\r\n");
	}
	Sent_Data[4] = Wireless_Mode + '0';
	Sent_Data[5] = Air_6in1_sensor + '0';
	
	

	
	Get_RS485_TempHumi();
	HAL_Delay(2000);
	Get_RS485_TempHumi();
	HAL_Delay(2000);
	Get_RS485_TempHumi();
	
	
	bstim_cnt = 0;
	
	while(1)
	{
					
		if(FL_GPIO_GetInputPin(WAKEUP0_GPIO_Port,WAKEUP0_Pin)==0)
			{
				HAL_Delay(5);
				if(FL_GPIO_GetInputPin(WAKEUP0_GPIO_Port,WAKEUP0_Pin)==0)
				{
					SysPrintf("key down...\r\n");
					NIC_Sent_Flag = 1;
					Sent_Data[43] = '2';
					SentTimes++;
				}
			}
		
		
		if((bstim_cnt%Period_Sample==0) || (NIC_Sent_Flag==1))
		{
			
			SysPrintf(">>MeasureTimes=%d\r\n",MeasureTimes);
			Get_PM_Data();
			Get_RS485_TempHumi();
			Get_Ordor_Data();
			
			
			if( (MeasureData.PM2_5 > PM2_5_High_th) && (Alarm_Status==0) )
			{
				SysPrintf("PM2.5 exceed alarm high threshold...\r\n");
				Alarm_cnt = bstim_cnt;
				MeasureData.AlarmFlag = 1;
				Alarm_Status = 1;
				Alarm_Sent_Flag = 1;
				Sent_Data[43] = '1';
				SentTimes++;
			}
			
			else if( (MeasureData.PM2_5 < PM2_5_Low_th) && (Alarm_Status==1) && (bstim_cnt-Alarm_cnt>=Alarm_Normal_Interval) )
			{
				SysPrintf("PM2.5 below alarm low threshold...\r\n");
				Alarm_Status = 0;
				MeasureData.AlarmFlag=0;
				Alarm_Sent_Flag = 1;
				Sent_Data[43] = '3';
				SentTimes++;
			}
			
				
			
			
					
			else if(MeasureTimes%PeriodSent_MeasureTimes==0)
			{
				SysPrintf("period upload...\r\n");
				Period_Sent_Flag = 1;
				Sent_Data[43] = '0';
				SentTimes++;
			}
			
			
			
			
			/*
			else if(MeasureTimes==60) 
			{
				SysPrintf("sent a new packet...\r\n");
				Period_Sent_Flag = 1;
				Sent_Data[43] = '0';
				SentTimes++;
			}
			*/
			
			
			
			else
			{
				;
			}
			
			
			
			
			
			if( (NIC_Sent_Flag==1)||(Alarm_Sent_Flag==1)||(Period_Sent_Flag==1) )
			{
				if(Wireless_Mode==Nb_Mode)
				{
					SysPrintf("NB-IoT sent data\r\n");
					Nb_Data_Communication();
					if(Bc26_Initial_Flag==FALSE)
					{
						Bc26_Initial_Flag=BC26_PowerStartAndSleep();
						SocketId=-1;
					}				
				 }
				else if(Wireless_Mode==Lora_Mode)   
				{					
					SysPrintf("LoRa sent data\r\n");
					if(LoRa_Detect==1)
					{
						Lora_Data_Communication();
					}
					else
					{
						if(Check_MHL10()==FALSE)
						{
							SysPrintf("LoRa detect error\r\n");
							LoRa_Detect = 0;
						}
						else
						{
							LoRa_Detect = 1;
							Lora_Data_Communication();
						}

					}					
				}
				
				else if(Wireless_Mode==LoRaWAN_Mode)   
				{					
					SysPrintf("LoRaWAN sent data\r\n");
					if(LoRaWAN_Detect==1)
					{
						LoraWAN_Data_Communication();
					}
					else
					{
						M120_Initial();
						if(LoRaWAN_Detect==1)
						{
							LoraWAN_Data_Communication();
						}
						else
						{
							SysPrintf("LoRa detect error\r\n");
							LoRaWAN_Detect = 0;
						}
					}					
				}
				
				else if(Wireless_Mode>=LoRa_1freq_Mode)   
				{
					SysPrintf("LoRa_1freq_Mode sent data\r\n");
				}
				else
				{
					;
				}
													 
			}
			
			NIC_Sent_Flag = 0;
			Alarm_Sent_Flag = 0;
			Period_Sent_Flag = 0;
			INT_KEY_DOWN=KEY_UP;
			
			MeasureTimes++;
			
			if(MeasureTimes%Reboot_MeasureTimes==0) 
			{
				SocketId=-1;
				
				if(Wireless_Mode==Nb_Mode)
				{
					SysPrintf(">>wakeup bc26\r\n");
					BC26_EINT3V3_H;
					HAL_Delay(30);
					BC26_EINT3V3_L;
					HAL_Delay(30);
					
				}
				else if(Wireless_Mode==LoRaWAN_Mode)
				{
					SysPrintf(">>wakeup M120L\r\n");
					M120_Wakeup_INT();
				}
				else if((Wireless_Mode==Lora_Mode) || (Wireless_Mode==LoRa_1freq_Mode))
				{
					SysPrintf(">>wakeup MHL10\r\n");		
					Wakeup_MHL10_HW();
				}
				else
				{
					;
				}
				SysPrintf(">>system reboot>>>\r\n");
				NVIC_SystemReset();
			}
		
			
			if( (Simcard_exist==0x00) && (Wireless_Mode==Nb_Mode) ) 
			{
				SysPrintf("not found simcard and poweroff bc26\r\n");		
				NB_PW_OFF;
				SocketId=-1;
				Send_err_time=0;
			}
			
		}

		
		HAL_Delay(100);
	
		
	}
	
	
	
	
	
	
	
	
	
	
    while(1)
    {     

    }

}


